package com.zhangtai.modules.service.baseFromMssql;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.zhangtai.Neusoft.service.NeuEmployeeBaseInfoService;
import com.zhangtai.config.AsyncEmployeeMethod;
import com.zhangtai.modules.controller.admin.JobController;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.dao.ImgUrlDao;
//import com.zhangtai.modules.dao.ssqlDao.BpmUserDao;
//import com.zhangtai.modules.dao.ssqlDao.JobDaoMssql;
import com.zhangtai.modules.dao.TbOrgEhrDao;
import com.zhangtai.modules.dto.JobDto;
import com.zhangtai.modules.dto.JobLevelDto;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.common.Nativeplace;
import com.zhangtai.modules.entity.common.OrgEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.orgin.TbOrgEhrEntity;
import com.zhangtai.modules.entity.salary.OrgLineEntity;
import com.zhangtai.modules.entity.salary.OrgSystemEntity;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.utils.R;
import com.zhangtai.utils.TypeCastUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@Slf4j
@Api(tags="后端通用接口")
public class BaseMssqlServiceImpl {
    @Autowired
    private TbOrgEhrDao orgEhrDao;

    @Autowired
    private RedisTemplate redisTemplate;
    //    @Autowired
//    private JobDaoMssql jobDaoMssql;
//
//    @Autowired
//    private BpmUserDao bpmUserDao;
    @Autowired
    private ImgUrlDao imgUrlDao;
    @Autowired
    private JobController jobController;
    @Autowired
    private AsyncEmployeeMethod asyncEmployeeMethod;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
//    @Autowired
//    private NeuEmployeeBaseInfoService neuEmployeeBaseInfoService;


    /**
     * 根据工号从mssql中查询用户
     * @param code
     * @return
     */
    @ApiOperation(value="根据工号从mssql中查询用户")
    public EmployeeInfoEntity finEmpFromMssqlByCode(String code){
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code",code).eq("is_delete",0));
        if (ObjectUtils.isEmpty(employeeInfoEntity)){
//            employeeInfoEntity = bpmUserDao.findEmpByCodeFromMssql(code);
        }
        if(ObjectUtils.isEmpty(employeeInfoEntity)){
            return null;
        }
        Long professionJoblevelId = employeeInfoEntity.getProfessionJoblevelId();
        Long managementJoblevelId = employeeInfoEntity.getManagementJoblevelId();
        if (managementJoblevelId!=null){
            employeeInfoEntity.setJobLevelType(2);
            employeeInfoEntity.setJobLevelId(managementJoblevelId);
        }else {
            employeeInfoEntity.setJobLevelType(1);
            employeeInfoEntity.setJobLevelId(professionJoblevelId);
        }
        //EmployeeInfoEntity oldInfo = employeeInfoService.getByIdE(employeeInfoEntity.getOid());
        List<EmployeeInfoEntity> list = new ArrayList<>();
        list.add(employeeInfoEntity);
        asyncEmployeeMethod.saveEhrEmployee(list);
//        neuEmployeeBaseInfoService.saveAndUpdateEmployeeInfoOne(code,employeeInfoEntity.getOid()+"");
//        neuEmployeeBaseInfoService.saveEmployeeInfoList(code);
        return employeeInfoEntity;
    }

    /**
     * 根据工号从mssql中查询用户
     * @param idCard
     * @return
     */
    @ApiOperation(value="根据工号从mssql中查询用户")
    public EmployeeInfoEntity finEmpFromMssqlByIdCard(String idCard){
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("idcard",idCard).eq("is_delete",0));
        if (ObjectUtils.isEmpty(employeeInfoEntity)){
//            bpmUserDao.findEmpByIdCardFromMssql(idCard);;
            List<EmployeeInfoEntity> list = new ArrayList<>();
            if(CollectionUtils.isEmpty(list)){
                return null;
            }
            employeeInfoEntity = list.get(0);
        }
        Long professionJoblevelId = employeeInfoEntity.getProfessionJoblevelId();
        Long managementJoblevelId = employeeInfoEntity.getManagementJoblevelId();
        if (managementJoblevelId!=null){
            employeeInfoEntity.setJobLevelType(2);
            employeeInfoEntity.setJobLevelId(managementJoblevelId);
        }else {
            employeeInfoEntity.setJobLevelType(1);
            employeeInfoEntity.setJobLevelId(professionJoblevelId);
        }
        //EmployeeInfoEntity oldInfo = employeeInfoService.getByIdE(employeeInfoEntity.getOid());
        List<EmployeeInfoEntity> list = new ArrayList<>();
        list.add(employeeInfoEntity);
        asyncEmployeeMethod.saveEhrEmployee(list);
//        neuEmployeeBaseInfoService.saveAndUpdateEmployeeInfoOne(employeeInfoEntity.getCode(),employeeInfoEntity.getOid()+"");
//        neuEmployeeBaseInfoService.saveEmployeeInfoList(employeeInfoEntity.getCode());
        return employeeInfoEntity;
    }

    /**
     * 查找所有岗位
     * @return
     */
    @ApiOperation(value="查找所有岗位")
    public List<JobDto> findAllJob(){
//        jobDaoMssql.findAllJob();
        return new ArrayList<>();


    }


    /**
     * 根据组织机构搜索职位
     * @return
     */
    @ApiOperation(value="根据组织机构搜索职位")
    public List<JobDto> findJobByKeyword(Long orgId){
//        jobDaoMssql.findJobByUnitId(orgId);
        return new ArrayList<>();
    }



    /**
     * 查找所有职级
     * @return
     */
    @ApiOperation(value="查找所有职级")
    public List<JobLevelDto> findJobLevel(){

        ArrayList<JobLevelDto> jobLevelDtos = new ArrayList<>();
//        jobDaoMssql.findAllJobLevel();
        List<JSONObject> allJobLevel = new ArrayList<>();

        for (JSONObject jsonObject : allJobLevel) {
            Long id = jsonObject.getLong("C_OID_CODEITEM");
            String name = jsonObject.getString("C_NAME");
            String typecode = jsonObject.getString("C_TYPECODE");
            String cCode = jsonObject.getString("C_CODE");
            JobLevelDto jobLevelDto = new JobLevelDto();
            jobLevelDto.setId(id);
            jobLevelDto.setName(name);
            jobLevelDto.setType(typecode);
            jobLevelDto.setCode(cCode);
            jobLevelDtos.add(jobLevelDto);
        }
        return jobLevelDtos;

    }

    /**
     * 根据id查询职级
     * @param id
     * @return
     */

    @ApiOperation(value="根据id查询职级")
    public JobLevelDto findJobLevelById(Long id){
//        jobDaoMssql.findJobLevelById(id);
        JSONObject jobLevelById = new JSONObject();
        if (ObjectUtils.isEmpty(jobLevelById)){
            return null;
        }
        JobLevelDto jobLevelDto = new JobLevelDto();
        jobLevelDto.setId(jobLevelById.getLong("C_OID_CODEITEM"));
        jobLevelDto.setType(jobLevelById.getString("C_TYPECODE"));
        jobLevelDto.setName(jobLevelById.getString("C_NAME"));
        return jobLevelDto;
    }






    /**
     * 查找组织机构
     * @return
     */
    @ApiOperation(value="查找组织机构")
    @GetMapping("/findAllOrg")
    public List<TbOrgEhrEntity> findAllOrg(){
       /* ArrayList<OrgEntity> orgEntities = new ArrayList<>();
//        jobDaoMssql.findAllOrg();
        List<JSONObject> allOrg = new ArrayList<>();
        for (JSONObject jsonObject : allOrg) {
            Long orgid = jsonObject.getLong("orgid");
            String orgname = jsonObject.getString("orgname");
            Long pareorgid = jsonObject.getLong("pareorgid");
            String pareorgname = jsonObject.getString("pareorgname");
            OrgEntity orgEntity = new OrgEntity();
            orgEntity.setId(orgid);
            orgEntity.setName(orgname);
            orgEntity.setPid(pareorgid);
            orgEntity.setPName(pareorgname);
            orgEntities.add(orgEntity);
        }*/
        List<TbOrgEhrEntity> tbOrgEhrEntities = orgEhrDao.selectList(null);

        return tbOrgEhrEntities;

    }
    @GetMapping("/findAllOrg/listTree")
    public List<TbOrgEhrEntity> orgListTree() {
        List<TbOrgEhrEntity> tbOrgEhrEntities = orgEhrDao.selectList(null);
        List<TbOrgEhrEntity> collect = tbOrgEhrEntities.stream().filter(item -> {
            return item.getCategory() == 0;
        }).map(menu -> {
            menu.setChildren(getchildrens(menu, tbOrgEhrEntities));
            return menu;
        }).collect(Collectors.toList());
        System.out.println(collect);
        return collect;
    }

    //递归查找
    private List<TbOrgEhrEntity> getchildrens(TbOrgEhrEntity root, List<TbOrgEhrEntity> all) {
        List<TbOrgEhrEntity> children = all.stream().filter(org -> {
            return org.getParrorgid()==root.getOrgid();
        }).map(org1 -> {
            //找到子菜单
            org1.setChildren(getchildrens(org1, all));
            return org1;
        }).collect(Collectors.toList());
        return children;
    }



    /**
     * 根据id查找组织机构
     * @return
     */
    @ApiOperation(value="根据id查找组织机构")
    public OrgEntity findOrgById(Long orgid){
//        jobDaoMssql.findOrgById(orgid);
        JSONObject jsonObject = new JSONObject();
        if (ObjectUtils.isEmpty(jsonObject)){
            return null;
        }
        OrgEntity orgEntity = new OrgEntity();
        orgEntity.setId(jsonObject.getLong("orgid"));
        orgEntity.setName(jsonObject.getString("orgname"));
        orgEntity.setPid(jsonObject.getLong("pareorgid"));
        orgEntity.setPName(jsonObject.getString("pareorgname"));
        return orgEntity;

    }



    /**
     *籍贯树
     * @return
     */
    @ApiOperation(value="查找籍贯树")
    public List<Nativeplace> findAllNativeplace(){

        ArrayList<Nativeplace> nativeplaces = new ArrayList<>();
//        jobDaoMssql.findAllNativeplace();
        List<JSONObject> allNativeplace = new ArrayList<>();
        for (JSONObject jsonObject : allNativeplace) {
            Nativeplace nativeplace = new Nativeplace();
            nativeplace.setId(jsonObject.getLong("C_OID_CODEITEM"));
            nativeplace.setName(jsonObject.getString("C_NAME"));
            nativeplace.setCode(jsonObject.getLong("C_CODE"));
            nativeplace.setParentId(jsonObject.getLong("C_PARANTID"));
            nativeplaces.add(nativeplace);
        }
        return nativeplaces;

    }

    /**
     * 查询所有体系
     * @return
     */
    @ApiOperation(value="查询所有体系")
    public List<OrgSystemEntity> findAllOrgSystemEntity(){

        ArrayList<OrgSystemEntity> orgSystemEntities = new ArrayList<>();
//        jobDaoMssql.findAllOrgSystemEntity();
        List<JSONObject> allOrgSystemEntity = new ArrayList<>();
        for (JSONObject jsonObject : allOrgSystemEntity) {
            OrgSystemEntity orgSystemEntity = new OrgSystemEntity();
            orgSystemEntity.setId(jsonObject.getLong("C_CODE"));
            orgSystemEntity.setName(jsonObject.getString("C_NAME"));
            orgSystemEntities.add(orgSystemEntity);

        }
        return orgSystemEntities;
    }


    /**
     * 查询所有条线
     * @return
     */
    @ApiOperation(value="查询所有条线")
    public List<OrgLineEntity> findAllOrgLineEntity(){

        ArrayList<OrgLineEntity> orgSystemEntityArrayList = new ArrayList<>();
//        jobDaoMssql.findAllOrgLineEntity();
        List<JSONObject> allOrgLineEntity = new ArrayList<>();
        for (JSONObject jsonObject : allOrgLineEntity) {
            OrgLineEntity orgLineEntity = new OrgLineEntity();
            orgLineEntity.setId(jsonObject.getLong("C_CODE"));
            orgLineEntity.setName(jsonObject.getString("C_NAME"));
            orgSystemEntityArrayList.add(orgLineEntity);
        }
        return orgSystemEntityArrayList;
    }

    @ApiOperation(value="根据id查找体系")
    public OrgSystemEntity findSystemById(Long id){
//       jobDaoMssql.findSystemById(id);

        JSONObject jsonObject = new JSONObject();
        if (ObjectUtils.isEmpty(jsonObject)){
            return null;
        }
        OrgSystemEntity orgSystemEntity = new OrgSystemEntity();
        orgSystemEntity.setId(jsonObject.getLong("C_CODE"));
        orgSystemEntity.setName("C_NAME");
        return orgSystemEntity;
    }

    @ApiOperation(value="根据id查找条线")
    public OrgSystemEntity findLineById(Long id){
//        jobDaoMssql.findLineById(id);
        JSONObject jsonObject = new JSONObject();
        if (ObjectUtils.isEmpty(jsonObject)){
            return null;
        }
        OrgSystemEntity orgSystemEntity = new OrgSystemEntity();
        orgSystemEntity.setId(jsonObject.getLong("C_CODE"));
        orgSystemEntity.setName(jsonObject.getString("C_NAME"));
        return orgSystemEntity;
    }

    /**
     * 根据jobId查找job
     * @param id
     * @return
     */
    @ApiOperation(value="根据id查找岗位")
    public JobDto findJobById(Long id){
//        jobDaoMssql.findById(id);
        JobDto byId = new JobDto();
        return byId;
    }

    /**
     * 查找所有招聘网站
     * @return
     */
    @ApiOperation(value="查找所有招聘网站")
    public List<JSONObject> findRecruitWeb(){
//        jobDaoMssql.findRecruitWeb();
        List<JSONObject> recruitWeb = new ArrayList<>();
        return recruitWeb;
    }


    /**
     * 根据体系名称莫查询获取体系id集合
     * @return
     */
    @ApiOperation(value="根据体系名称莫查询获取体系id集合")
    @GetMapping("/findSystemIdByName")
    public List<Long> findSystemIdByName(@RequestParam("systemName") String systemName){
//        jobDaoMssql.findSystemIdByName(systemName);/
        List<Long> systemIdByName = new ArrayList<>();
//        log.info("systemIdByName:{}",systemIdByName);
        return systemIdByName;

    }

    /**
     * 根据条线名称莫查询获取条线id集合
     * @return
     */
    @ApiOperation(value="根据体系名称莫查询获取体系id集合")
    @GetMapping("/findLineIdByName")
    public List<Long> findLineIdByName(@RequestParam("lineName") String lineName){
//        jobDaoMssql.findLineIdByName(lineName);
        List<Long> systemIdByName = new ArrayList<>();
//        log.info("systemIdByName:{}",systemIdByName);
        return systemIdByName;

    }

    /**
     * 根据职位名称查找职位id
     * @param jobName
     * @return
     */
    @ApiOperation(value="根据职位名称查找职位id")
    @GetMapping("/findJobIdByJobName")
    public List<Long> findJobIdByJobName(@RequestParam("jobName") String jobName){
//        jobDaoMssql.findJobIdByJobName(jobName);
        List<Long> jobIdByJobName = new ArrayList<>();
        return jobIdByJobName;
    }

    public List<Long> finOrgByOrgName(String orgName){
//        jobDaoMssql.findOrgByName(orgName);
        List<Long> orgList = new ArrayList<>();
        return orgList;
    }

    @GetMapping("/like")
    public  String like(){
//        jobDaoMssql.findSystemIdByName("集团");
        List<Long> jituan = new ArrayList<>();
        List<ImgUrlEntity> imgUrlEntities = imgUrlDao.selectList(null);
        System.out.println(imgUrlEntities);
        System.out.println(jituan);
        return "ok";
    }









    public List<Map<String,Object>> finOrgByPid(List<OrgEntity> bpmOrgList, Long pid,ArrayList<Long> list){
        ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
        for (OrgEntity orgEntity : bpmOrgList) {
            if (orgEntity.getPid().equals(pid)&&!"撤销禁用".equals(orgEntity.getName())){
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("value", orgEntity.getId());
                hashMap.put("title", orgEntity.getName());
                hashMap.put("parentOrg", orgEntity.getPName());
                hashMap.put("pareorgId", orgEntity.getPid());
                List<Map<String,Object>> childrenList = finOrgByPid(bpmOrgList, orgEntity.getId(),list);
                hashMap.put("children",childrenList);
                jobController.orgAllChildrenMap.put(orgEntity.getId(),getOrgId(hashMap));
                arrayList.add(hashMap);
            }
        }

        Collections.sort(arrayList, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Long l2 = TypeCastUtils.toLong(o2.get("pareorgId"));
                Long l1 = TypeCastUtils.toLong(o1.get("pareorgId"));
                Long i=l2-l1;
                int i1 = TypeCastUtils.toInt(o1.get("value"));
                int i2 = TypeCastUtils.toInt(o2.get("value"));
                int toInt = TypeCastUtils.toInt(i);
                return toInt;
            }
        });

        return arrayList;

    }


    /**
     * 处理部门id
     * @param hashMap
     * @return
     */
    public List<Long> getOrgId(Map<String,Object> hashMap){
        List<Long> ids = new ArrayList<>();
        List<Map<String, Object>> childrenList = (List<Map<String, Object>>) hashMap.get("children");
        ids.add((Long)hashMap.get("value"));
        for(Map<String,Object> childrenMap :childrenList){
            List<Long> childrenIds = getOrgId(childrenMap);
            ids.addAll(childrenIds);
        }
        return ids;

    }


    public List<Map<String,Object>> findNativePlaceByPid(List<Nativeplace> allNativeplace, Long pid){
        ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
        for (Nativeplace nativeplace : allNativeplace) {
            if (nativeplace.getParentId().equals(pid)){

                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("value", nativeplace.getId());
                hashMap.put("title", nativeplace.getName());

                hashMap.put("code", nativeplace.getCode());
                List<Map<String, Object>> nativePlaceByPid = findNativePlaceByPid(allNativeplace, nativeplace.getId());
                if (!CollectionUtils.isEmpty(nativePlaceByPid)){
                    hashMap.put("children",nativePlaceByPid);
                }

//                if (!"撤销禁用".equals(orgEntity.getOrgname())){
                arrayList.add(hashMap);
//                }

            }
        }


        return arrayList;

    }

    /**
     * 根据附件路径，批量插入td_img_url
     * @param urlIds  参数：附件路径逗号隔开
     * @param oId  参数：员工ID
     * @return
     */
    public R urlIds(String urlIds,Long oId) {

        String[] urlId = urlIds.split(",");
        for (int i = 0; i < urlId.length; i++) {
            ImgUrlEntity imgUrl = new ImgUrlEntity();
            imgUrl.setUrl(urlId[i]);
            imgUrl.setOid(oId);

            //单个插入img_url表
            imgUrlDao.insert(imgUrl);
        }
        return R.ok();
    }



}
